<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>报名</title>
    <meta name="description" content="报名" />
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="./css/frozen.css">
    <link rel="stylesheet" href="./css/sign.css">
    <link rel="stylesheet" href="../common/css/plugins.css" media="screen" title="no_title" charset="utf-8">
    <script src="js/jquery.min.js"></script>
    <style>
        .detailHeader .resource video {
            height: 7.6rem;
        }

        .detailHeader .resource audio {
            position: absolute;
            bottom: 0;
        }

        .rule p {
            word-break: break-all;
        }

        .layui-m-layer0 .layui-m-layerchild {
            background-color: #e5cb86 !important;
        }

        .layui-m-layerbtn {
            background-color: #e5cb98 !important;
        }

        .layui-m-layerbtn span[yes] {
            color: #901d1d !important;
        }

        .layui-m-layerbtn span[no] {
            color: #901d1d !important;
        }
        .layui-m-layercont {
            color: #901d1d !important;
        }

        #btnWrap {
            width: 100%;
            background: #eeeeee;
            padding-top: 20px;
            padding-bottom: 1px;
            position: relative;
        }

        #btnWrap .wybm0 {
            display: block;
            margin: 0 auto;
            width: 71%;
        }

        #btnWrap .wybm0 img {
            width: 100%;
        }
        #actDesBox *{
            color: #333 !important;
        }
        #bmWrap .ui-form-item textarea {
            width: 100%;
            padding: 10px;
            height: 88px;
            border: 1px solid #eee;
        }
        .ui-form-item{
            height: auto;
        }
    </style>
</head>

<body>
<div id="bmMain">
</div>
<script src="js/artTemplate/artTemplate.js"></script>
<script src='js/vote-tpl.js'></script>
<script src="js/layer/layer.js"></script>
<link rel="stylesheet" type="text/css" href="css/webuploader.css">
<script src="js/webuploader.html5only.min.js"></script>
<script src="js/uploader.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="../common/js/weixinshare.js"></script>
<script>
    function QRCode(qrcode){
        var $mask = $('<div class="mask-layer">' +
            '             <div class="cover"></div>' +
            '             <div class="content">'+
//            '                 <div class="close icon"></div>' +
            '                 <div class="qr-code"></div>' +
            '                 <div class="slogan">扫描二维码,关注公众号后参与活动</div>' +
            '             </div>' +
            '         </div>');
        $mask.find('.close.icon').click(function(e){
            $mask.remove();
        });
        return {
            open: function(){
                if(qrcode){
                    $mask.find('.qr-code').html('<img src="'+qrcode+'" alt="二维码"/>');
                }
                $('body').append($mask);
            },
            close: function(){
                $mask.remove();
            }
        }
    }
    function forbidShare() {
        function onBridgeReady() {
            WeixinJSBridge.call('hideOptionMenu');
        }

        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady();
        }
    }
</script>
<script>
    window.addEventListener("popstate",function(e){
        window.location=window.location.href;
    })
    var isWechat = false,isAPP = false,isFollow = false,isCode=false,isPart=false,activities={},vote_token='';
    var url = '/', act_info = '';
    window.parameter = GetRequest(window.location.href);
    window.bmData = {}; //收集弹窗的数据
    //window.parameter.vote_id = 'ecefbde8-ac8f-41bf-b017-bb9b0e4e68d4';
    window.commonData = {};
    /*
     * 获取?后面的参数并返回 json 对象
     */
    function GetRequest(url) {
        if (!url || url.indexOf('?') == -1) {
            return {};
        }
        var url = url.split('?')[1].split('#')[0]; //获取url中"?"符后"#"前的字串
        var theRequest = new Object();
        var str = decodeURI(url);
        var strs;
        if (str.indexOf("&") != -1) {
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        } else {
            theRequest[str.split("=")[0]] = unescape(str.split("=")[1]);
        }
        theRequest['vote_id'] = theRequest['act_id'];
        return theRequest;
    }

    function bindEvent() {
        //IOS中激活a标签active事件
        var a = document.getElementsByTagName('a');
        for (var i = 0; i < a.length; i++) {
            a[i].addEventListener('touchstart', function () {
            }, false);
        }
        document.body.addEventListener('touchstart', function () {
        });
        $('#bmBtn').on('click',function () {
            if (!isPart&&!window.parameter.uid && !window.parameter.mfSign) {
                if (activities.publishing.app.app_urls[0]) {
                    layer.open({
                        content: '请下载APP参与报名'
                        , btn: ['确定', '取消']
                        , yes: function (index) {
                            location.href = activities.publishing.app.app_urls[0];
                            layer.close(index);
                        }
                    });
                } else {
                    layer.open({
                        content: '请下载APP参与报名'
                        , btn: '确定'
                    });
                }
                return;
            }

            if (!isPart&&!window.parameter.uid && window.parameter.mfSign) {
                var paramJson = GetRequest(window.location.href);
                var param = '';
                //有noLogin参数
                if (window.location.search.indexOf('noLogin') != -1) {
                    $.each(paramJson, function (val, i) {
                        if (val != 'noLogin') {
                            param += val + '=' + paramJson[val] + '&'
                        }
                    });
                    param = param.slice(0, -1);
                    window.location.href = window.location.origin + window.location.pathname + '?' + param + '&noLogin=true';
                } else {//没noLogin参数
                    window.location.href = window.location.origin + window.location.pathname + window.location.search + '&noLogin=true';
                }
                return;
            }

            var params = $('#bmForm').serializeArray()
            var values = {};
            //将serializeArray的数据处理成json
            for (var item in params) {

                if (bmData.checkboxData.indexOf(params[item].name) != -1 && !values[params[item].name]) {
                    values[params[item].name] = [];
                }

                if ($.isArray(values[params[item].name])) { //处理多选框的情况,将并行的多选处理成数组
                    values[params[item].name].push(params[item].value);
                } else {
                    values[params[item].name] = params[item].value;
                }

            }

            var UploaderData = {};
            $.each(window.mfUploaderData, function (key, val) {
                UploaderData[key] = [];
                $.each(val, function (key1, val2) {
                    UploaderData[key].push(val2.src);
                })
            })
            $.extend(values, UploaderData);
            var checkStatus = checkForm(values, window.bmData.widgets);
            if (checkStatus) { //未检测通过不让提交
                bmCallBack(window.parameter.vote_id, values);
            }
        })

        $('#wybm').on('click',function () {
            var end_time = act_info.end_time.substring(0,19).replace(/-/g,'/');
            if((new Date(end_time).getTime())- (new Date().getTime())<0){
                layer.open({
                    content: '活动已结束'
                    , btn: '确定'
                });
                return false;
            }
            if(!isPart&&!window.parameter.uid && !window.parameter.mfSign){
                if (activities.publishing.app.app_urls[0]) {
                    layer.open({
                        content: '请下载APP参与报名'
                        , btn: ['确定', '取消']
                        , yes: function (index) {
                            location.href = activities.publishing.app.app_urls[0];
                            layer.close(index);
                        }
                    });
                } else {
                    layer.open({
                        content: '请下载APP参与报名'
                        , btn: '确定'
                    });
                }
                return;
            }

            if (!isPart&&!window.parameter.uid && window.parameter.mfSign) {
                var paramJson = GetRequest(window.location.href);
                var param = '';
                //有noLogin参数
                if (window.location.search.indexOf('noLogin') != -1) {
                    $.each(paramJson, function (val, i) {
                        if (val != 'noLogin') {
                            param += val + '=' + paramJson[val] + '&'
                        }
                    })
                    param = param.slice(0, -1);
                    window.location.href = window.location.origin + window.location.pathname + '?' + param + '&noLogin=true';
                } else { //没noLogin参数
                    window.location.href = window.location.origin + window.location.pathname + window.location.search + '&noLogin=true';
                }
                return;
            }
            $('#bmMain').hide();
            $('#bmWrap').fadeIn();
            window.history.pushState("", "enroll", window.location.search);
        })
    }

    /**
     * 验证sign
     */
    function signCallBack() {
        layer.open({
            type: 2,
            shadeClose: false
        });
        var data = {};
        for (x in window.parameter) {
            if (x == 'vote_id') {
                continue;
            }
            data[x] = window.parameter[x]
        }

        $.ajax({
            url: url + 'api/app/sign/mf.php',
            data: data,
            type: 'get',
            success: function (ajaxData) {
                if (ajaxData.code == '200') {
                    getBmDateCallBack();
                    vote_token = ajaxData.vote_token;
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: '活动链接错误'
                    });
                }
            }
        })
    }
    if(window.parameter['ways']!='wechat'){
        //没有uid 和 userid 不验签
        if (!window.parameter.userid && !window.parameter.uid) {
            getBmDateCallBack();
        } else {
            signCallBack();
        }
    }else{
        isSignPass = 1;
        vote_token = window.parameter['vote_token'];
        getBmDateCallBack();
    }

    /**
     * 获取报名信息
     */
    function getBmDateCallBack() {
        $.ajax({
            url: url + 'apply/widgets/' + window.parameter.vote_id,
            type: 'get',
            success: function (ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    act_info = ajaxData.data.activity;
                    var bmMainHtml = voteTpl.bmMainHtml({
                        data: ajaxData.data
                    });
                    var bmFormHtml = voteTpl.bmFormHtml({
                        data: ajaxData.data.widgets
                    });
                    bmData.widgets = ajaxData.data.widgets;
                    $('title').html(ajaxData.data.activity.name);
                    $('#bmMain').html(bmMainHtml);
                    $('#bmDes').html(ajaxData.data.activity.description);
                    $('body').append(bmFormHtml);
                    bmData.checkboxData = [];
                    $.each(ajaxData.data.widgets, function (key, val) {
                        if (val.type == 'checkbox') {
                            bmData.checkboxData.push(val.name);
                        }
                    })
                    uploaderCallBack(bmData.widgets);
                    bindEvent();
                    //===============================
                    activities = ajaxData.data.activity;
                    isWechat = (window.parameter.ways == 'wechat');//是否开启微信
                    isAPP = (activities.publishing.app.is_open =='on');//是否开启APP
                    isFollow = (window.parameter['following']!=1);//是否关注
                    isCode = Boolean(activities.publishing.wechat.qr_code[0]);//是否上传二维码
                    if(isWechat){
                        if(isFollow){
                            isPart = true;
                        }else{
                            if(isCode){
                                var qrCode = QRCode(activities.publishing.wechat.qr_code[0]).open();
                            }else{
                                isPart = true;
                            }
                        }
                    }else{
                        //APP
                    }
                    if (typeof wxshare != 'undefined' && (activities.shares.isopen == 'on' || activities.shares.isopen == '1')) {
                        var shareLink = '';
                        if(isWechat){
                            shareLink =window.location.origin+'/wechat/shares?id='+window.parameter.act_id;
                        }else{
                            shareLink = window.location.origin + location.pathname + '?act_id=' + wxshare.getUrlParam('act_id');
                        }
                        wxshare.share({
                            title: activities.shares.title,
                            desc: activities.shares.content,
                            link: shareLink,
                            imgUrl: activities.shares.thumb,
                        });
                    }else{
                        forbidShare();
                    }
                    //===========================
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message,
                    });
                }
            }
        })
    }

    /**
     * 检查表单必填项是否填了
     * checkdata : 待检查的数据
     * data : 待检测数据需要满足的规则
     * @return  object
     */

    function checkForm(checkdata, data) {
        var checkStatus = true;
        $.each(data, function (key, val) {
            if (val.required) {
                if (!checkdata[val.name]) {
                    layer.open({
                        skin: 'msg',
                        time: 5 //2秒后自动关闭'
                        ,
                        content: val.text + '是必填项!请填写后再提交!'
                    })
                    checkStatus = false;
                    return false;
                }
            }
            if(val.name=='mobile'&&!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(checkdata[val.name]))){
                layer.open({
                    skin: 'msg',
                    time: 5 //2秒后自动关闭'
                    ,
                    content: val.text + '输入不正确！'
                });
                checkStatus = false;
                return false;
            }
            if(val.type=='textarea'&&checkdata[val.name].length>50){
                layer.open({
                    skin: 'msg',
                    time: 5 //2秒后自动关闭'
                    ,
                    content: val.text + '不超过50个字符！'
                });
                checkStatus = false;
                return false;
            }

        })

        return checkStatus;
    }

    function upperCase(key, name) {
        if (key == 'mobile') {
            var m = document.getElementsByName(key)[0].value;
            if (!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(m))) {
                layer.open({
                    skin: 'msg',
                    time: 5 //2秒后自动关闭'
                    ,
                    content: name + '输入不正确！'
                })
                return false;
            }
        }

        return true;
    }
    /**
     * 报名
     *  `vote_id`: 活动id
     */
    function bmCallBack(vote_id, data) {
        var index = layer.open({
            type: 2,
            shadeClose: false
        });
        $.ajax({
            url: url + 'apply/' + vote_id,
            data: data,
            type: 'POST',
            success: function (ajaxData) {
                layer.close(index);
                if (ajaxData.code == 200) {
                    layer.open({
                        time: 1,
                        className: 'messageStyle',
                        content: '报名成功'
                    });
                    window.location.href = window.location;
                } else {
                    if(ajaxData.message){
                        layer.open({
                            className: 'messageStyle',
                            content: ajaxData.message
                        });
                    }else{
                        layer.open({
                            className: 'messageStyle',
                            content: '网络不给力，请稍后重试！'
                        });
                    }

                }
            }
        })
    }

    /**
     *  上传按钮绑定事件
     *  `item_id`: 候选项的id
     *  `uid`: 用户id
     */
    function uploaderCallBack(data) {

        $.each(data, function (i, key) {

            if (key.type == 'file') {

                var accept = {};
                if (key.file_type == "image") { //图片
                    accept = {
                        title: 'Images',
                        extensions: 'gif,jpg,jpeg,bmp,png',
                        mimeTypes: 'image/*',
                        thumbnailWidth: 80,
                        thumbnailWidth: 80
                    }
                } else if (key.file_type == "voice") { //音频
                    accept = {
                        title: 'audio',
                        extensions: 'mp3,mp4,wma',
                        mimeTypes: 'audio/*',

                    }
                } else if (key.file_type == "video") { //视频
                    accept = {
                        title: 'video',
                        extensions: 'mp4,avi,wmv,mov',
                        mimeTypes: 'video/*',
                    }
                }
                $('#filePicker_' + key.name).mfUploader({
                    name: key.name,
                    list: "#fileList_" + key.name,
                    formData: key.file_type == "video" || key.file_type == "audio" ? {
                        type: key.file_type
                    } : {},
                    accept: accept,
                    fileNumLimit: key.max_allow_upload ? key.max_allow_upload : 1
                });
            }
        })
    }
</script>
</body>

</html>
